package com.springboot.mall.service.impl;

import com.springboot.mall.common.Constant;
import com.springboot.mall.exception.MallException;
import com.springboot.mall.exception.MallExceptionEnum;
import com.springboot.mall.filter.UserFilter;
import com.springboot.mall.model.entity.Cart;
import com.springboot.mall.model.entity.Order;
import com.springboot.mall.model.entity.OrderItem;
import com.springboot.mall.model.entity.Product;
import com.springboot.mall.model.mappers.CartMapper;
import com.springboot.mall.model.mappers.OrderItemMapper;
import com.springboot.mall.model.mappers.OrderMapper;
import com.springboot.mall.model.mappers.ProductMapper;
import com.springboot.mall.model.request.CreateOrderRequest;
import com.springboot.mall.model.vo.CartVO;
import com.springboot.mall.service.CartService;
import com.springboot.mall.service.OrderService;
import com.springboot.mall.utils.OrderCodeFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/*
 *
 *
 *@data 2022-05-15
 */

@Service("orderService")
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CartService cartService;
    //返回的是一个orderNo
    @Autowired
    private ProductMapper productMapper;

    @Autowired
    private CartMapper cartMapper;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;


    //遇到什么异常都会回滚
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String create(CreateOrderRequest createOrderRequest){
        //拿到用户ID
        Integer userId = UserFilter.currentUser.getId();
        //从购物车查找已经勾选的商品
        List<CartVO> cartVOList = cartService.list(userId);
        ArrayList<CartVO> cartVOListTemp = new ArrayList<>();
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            if (cartVO.getSelected().equals(Constant.Cart.CHECKED)){
                cartVOListTemp.add(cartVO);
            }
        }
        cartVOList = cartVOListTemp;

        //如果购物车为空，报错（淘宝提示的是：您还未挑选商品）
        if (CollectionUtils.isEmpty(cartVOList)){
            throw new MallException(MallExceptionEnum.CART_EMPTY);
        }
        //判断商品是否存在，上下架状态，库存
        validStatusAndStock(cartVOList);
        //把购物车对象转为订单item对象
        List<OrderItem> orderItemList = cartVOListToOrderItem(cartVOList);
        //扣库存
        for (int i = 0; i < orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            Product product = productMapper.selectByPrimaryKey(orderItem.getProductId());
            int stock = product.getStock() - orderItem.getQuantity();
            if (stock < 0){
                throw new MallException(MallExceptionEnum.NOT_ENOUGH);
            }
            product.setStock(stock);
            productMapper.updateByPrimaryKeySelective(product);
        }
        //扣库存成功：把购物车中的已勾选的商品删除
        cleanCart(cartVOList);
        //生成订单
        Order order = new Order();
        //生成订单号，有独立的规则
        String orderNo = OrderCodeFactory.getOrderCode(Long.valueOf(userId));
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setTotalPrice(totalPrice(orderItemList));
        order.setReceiverName(createOrderRequest.getReceiverName());
        order.setReceiverMobile(createOrderRequest.getReceiverMobile());
        order.setReceiverAddress(createOrderRequest.getReceiverAddress());
        order.setOrderStatus(Constant.OrderStatusEnum.NOT_PAID.getCode());
        order.setPostage(0);
        order.setPaymentType(1);
        //插入到Order表
        orderMapper.insertSelective(order);
        //循环保存每个商品到order_item表
        for (int i = 0; i <orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            orderItem.setOrderNo(order.getOrderNo());
            orderItemMapper.insertSelective(orderItem);
        }

        //把结果返回
        return orderNo;

    }

    private void validStatusAndStock(List<CartVO> cartVOList){
        for (int i = 0; i <cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            Product product = productMapper.selectByPrimaryKey(cartVO.getProductId());
            //判断商品是否存在，商品是否上架
            if (product == null || product.getStatus().equals(Constant.SaleStatus.NOT_SALE)){
                throw new MallException(MallExceptionEnum.NOT_SALE);
            }
            //判断商品库存
            if (cartVO.getQuantity() > product.getStock()){
                throw  new MallException(MallExceptionEnum.NOT_ENOUGH);
            }

        }
    }
    private List<OrderItem>  cartVOListToOrderItem(List<CartVO> cartVOList){
        List<OrderItem> oderItemList = new ArrayList<>();
        for (int i = 0; i <cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            OrderItem orderItem = new OrderItem();
            orderItem.setProductId(cartVO.getProductId());
            //记录商品快照信息
            orderItem.setProductImg(cartVO.getProductImage());
            orderItem.setProductName(cartVO.getProductName());
            orderItem.setUnitPrice(cartVO.getPrice());
            orderItem.setQuantity(cartVO.getQuantity());
            orderItem.setTotalPrice(cartVO.getTotalPrice());
            oderItemList.add(orderItem);
        }
        return oderItemList;

    }
    private  void cleanCart(List<CartVO> cartVOList){
        for (int i = 0; i < cartVOList.size(); i++) {
            CartVO cartVO = cartVOList.get(i);
            cartMapper.deleteByPrimaryKey(cartVO.getId());
        }
    }

    private Integer totalPrice(List<OrderItem> orderItemList){
        Integer totalPrice = 0;
        for (int i = 0; i <orderItemList.size(); i++) {
            OrderItem orderItem = orderItemList.get(i);
            totalPrice += orderItem.getTotalPrice();
        }
        return totalPrice;
    }

}
